import { fetchHome } from '../../services/home/home';
// import {
//   fetchGoodsList
// } from '../../services/good/fetchGoods';
import Toast from 'tdesign-miniprogram/toast/index';
import { getBanner, getCategoryList, getJxStoreList, getJxGoodsList } from '../../api/index';
Page({
  data: {
    loading: true,
    imgList: [],
    imgSrcs: [],
    tabList: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: {
      type: 'dots',
    },
    swiperImageProps: {
      mode: 'scaleToFill',
    },
    barConTop: 0,
    barConHeight: 0,
    visible: false,
    marketInfo: {},
    marketList: [
      {
        id: 1,
        status: 1,
        name: '筑美农贸市场',
        addr: '杭州市萧山区市心北路777号',
        reachType: 1,
        distance: '1.35km',
      },
      {
        id: 2,
        status: 1,
        name: '萧山中心农贸市场',
        addr: '杭州市萧山区市心北路777号',
        reachType: 2,
        distance: '1.35km',
      },
      {
        id: 3,
        status: 2,
        name: '宁围农贸市场',
        addr: '杭州市萧山区利华路553号120米',
        reachType: 2,
        distance: '1.35km',
      },
      {
        id: 4,
        status: 2,
        name: '新华农贸市场',
        addr: '杭州市萧山区市心北路777号',
        reachType: 3,
        distance: '1.35km',
      },
      {
        id: 5,
        status: 1,
        name: '农贸市场',
        addr: '杭州市萧山区利华路553号120米',
        reachType: 3,
        distance: '1.35km',
      },
    ],
    categoryList: [],
    jxTabList: [
      {
        name: '精选店铺',
        subName: '优质商家 放心购',
      },
      {
        name: '精选商品',
        subName: '优选好物 为您推荐',
      },
    ],
    tabIndex: 0,
    linkBoxList: [
      {
        imgSrc: '../../assets/img/img-find-store.png',
      },
      {
        imgSrc: '../../assets/img/img-good-select.png',
      },
    ],
  },

  goodListPagination: {
    index: 1,
    num: 20,
  },

  privateData: {
    tabIndex: 0,
  },

  onShow() {
    // this.getTabBar().init();
  },

  onLoad() {
    setTimeout(() => {
      this.setData({
        loading: false,
      });
    }, 2000);
    this.init();
  },

  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.goodListPagination.index++;
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    this.init();
  },

  async init() {
    this.initBarCon();
    this.loadHomePage();
  },

  initBarCon() {
    // 状态栏信息-高度
    const status = wx.getSystemInfoSync();
    // 胶囊信息-高度及到顶高度
    const menu = wx.getMenuButtonBoundingClientRect();
    const barHeight = menu.height + (menu.top - status.statusBarHeight) * 2;
    this.setData({
      barConHeight: barHeight,
      barConTop: status.statusBarHeight,
    });
  },

  async loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });
    const banner = await getBanner(1);
    const imgSrcs = banner.map((item) => item.picUrl);
    const categoryList = await getCategoryList();
    this.setData({
      imgSrcs: imgSrcs,
      imgList: banner,
      categoryList: categoryList,
      pageLoading: false,
      marketInfo: this.data.marketList[0],
    });
    this.loadGoodsList(true);
    return false;
    fetchHome().then(({ swiper, tabList }) => {
      this.setData({
        tabList,
        imgSrcs: swiper,
        pageLoading: false,
        marketInfo: this.data.marketList[0],
      });
      this.loadGoodsList(true);
    });
  },
  toAddrList() {
    console.log('aaa');
    wx.navigateTo({
      url: '/pages/usercenter/address/list/index',
    });
  },
  tabChangeHandle(e) {
    this.privateData.tabIndex = e.detail;
    this.loadGoodsList(true);
  },

  onReTry() {
    this.loadGoodsList();
  },

  async loadGoodsList(fresh = false) {
    // if (fresh) {
    //   wx.pageScrollTo({
    //     scrollTop: 0,
    //   });
    // }

    this.setData({
      goodsListLoadStatus: 1,
    });

    const pageSize = this.goodListPagination.num;
    let pageIndex = this.goodListPagination.index;
    // let pageIndex = this.privateData.tabIndex * pageSize + this.goodListPagination.index + 1;
    if (fresh) {
      pageIndex = 1;
    }

    try {
      // const nextList = await fetchGoodsList(pageIndex, pageSize);
      let data = null;
      let params = {};
      if (this.data.tabIndex === 0) {
        params = {
          pageNo: pageIndex,
          pageSize: pageSize,
        };
        data = await getJxStoreList(params);
      } else {
        params = {
          pageNo: pageIndex,
          pageSize: pageSize,
        };
        data = await getJxGoodsList(params);
        data.list && data.list.map(t => {
          t.price = t.price && (t.price / 100).toFixed(2)
          return t
        })
      }

      this.setData({
        goodsList: fresh ? data.list : this.data.goodsList.concat(data.list),
        goodsListLoadStatus: 0,
      });

      // this.goodListPagination.index = pageIndex;
      // this.goodListPagination.num = pageSize;
    } catch (err) {
      this.setData({
        goodsListLoadStatus: 3,
      });
    }
  },

  goodListClickHandle(e) {
    const { index } = e.detail;
    const { spuId } = this.data.goodsList[index];
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}`,
    });
  },

  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },

  navToSearchPage() {
    wx.navigateTo({
      // url: '/pages/goods/search/index'
      url: '/pages/goods/nSearch/index',
    });
  },

  navToActivityDetail({ detail }) {
    // const { index: promotionID = 0 } = detail || {};
    // wx.navigateTo({
    //   url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    // });
    const { index = 0 } = detail || {};
    let url = ""
    if (index == 0) {
      url = "/pages/kaiye/kaiye"
    } else {
      url = "/pages/shangpuhuodong/shangpuhuodong"
    }
    wx.navigateTo({
      url: url
    });
  },
  handlePopup() {
    this.setData({
      visible: true,
    });
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    });
  },
  handleMarket(e) {
    console.log(e);
    this.setData({
      visible: false,
      marketInfo: e.currentTarget.dataset.item,
    });
  },
  tabClick(e) {
    const { index } = e.currentTarget.dataset;
    if (this.tabIndex === index) return;

    this.setData({
      tabIndex: index,
      goodsList: [],
    });
    this.goodListPagination.index = 1;
    this.goodListPagination.num = 20;

    this.loadGoodsList();
  },
  runPage(e) {
    const { index } = e.currentTarget.dataset;
    let url = '';
    if (index === 0) {
      url = '/pages/goods/findStore/index';
    } else {
      url = '/pages/lvlifangyouxuan/lvlifangyouxuan';
    }

    wx.navigateTo({
      url: url,
    });
  },
  runClassify(e) {
    const {id} = e.currentTarget.dataset
    wx.setStorageSync('categoryId', id)
    wx.switchTab({
      url: `/pages/goods/category/index`,
    });
  }
});
